package com.pox.guli.service.base.handler;

import com.pox.guli.common.base.result.R;
import com.pox.guli.common.base.result.ResultCodeEnum;
import com.pox.guli.common.base.util.ExceptionUtils;
import com.pox.guli.service.base.exception.PoXException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理器
 *
 * @Author PoX21s
 * @Date: 2022/6/1 20:32
 * @Version 1.0
 */

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 总异常处理
     *
     * @return com.pox.guli.common.base.result.R
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        // e.printStackTrace();
        // 记录到具体文件中
        log.error(ExceptionUtils.getMessage(e));
        return R.error();
    }

    /**
     * SQL语句错误
     *
     * @return com.pox.guli.common.base.result.R
     */
    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseBody
    public R error(BadSqlGrammarException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }

    /**
     * Json格式错误
     *
     * @return com.pox.guli.common.base.result.R
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public R error(HttpMessageNotReadableException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCodeEnum.JSON_PARSE_ERROR);
    }

    /**
     * 自定义异常处理
     *
     * @return com.pox.guli.common.base.result.R
     */
    @ExceptionHandler(PoXException.class)
    @ResponseBody
    public R error(PoXException e) {
        log.error(ExceptionUtils.getMessage(e));
        return R.error().message(e.getMessage()).code(e.getCode());
    }
}